<template>
  <div>
    <el-dialog
      v-model="props.isShow"
      :title="props.isAdd ? '添加' : '编辑'"
      center
      :before-close="cancel"
    >
      <el-form :model="form" :rules="rules" ref="roleRef">
        <el-form-item label="角色名称" prop="rolename" :label-width="formLabelWidth">
          <el-input v-model="form.rolename" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色权限" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            :data="store.getters['menu/getMenu']"
            show-checkbox
            node-key="id"
            default-expand-all
            check-strictly
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(roleRef)">取消</el-button>
          <el-button type="primary" @click="confirm(roleRef)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, defineEmits, onMounted } from "vue";
import { useStore } from "vuex";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { roleadd, roleedit, roleinfo } from "../../request/api";

const value1 = ref(true);

let store = useStore();

const formLabelWidth = "140px";

const form = ref({
  rolename: "", // 角色名称 string
  menus: "", // 角色权限 id数组 '2,3,4' 字符串
  status: 1, // 状态1正常2禁用 number
});

//定义 rules规则
const rules = {
  rolename: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur",
    },
    {
      min: 2,
      max: 6,
      message: "长度在 2 到 6 个字符",
      trigger: "blur",
    },
  ],
};

// 父传子
let props = defineProps({
  isShow: Boolean,
  isAdd: Boolean,
});

// 子传父
let emit = defineEmits(["cancel"]);

// 取消
// const cancel = () => {
//   emit("cancel");
//   form.value = {
//     rolename: "", // 角色名称 string
//     menus: "", // 角色权限 id数组 '2,3,4' 字符串
//     status: 1, // 状态1正常2禁用 number
//   };
//   // 清除规则验证
//   roleRef.value.resetFields()
//   // 重置权限 通过keys设置目前勾选的节点 使用此方法设置node-key属性
//   tree.value.setCheckedKeys([])
// };
let cancel = (formEl?: FormInstance | undefined) => {
  emit("cancel");
  form.value = {
    rolename: "", // 角色名称 string
    menus: "", // 角色权限 id数组 '2,3,4' 字符串
    status: 1, // 状态1正常2禁用 number
  };
  if (!formEl) return;
  roleRef.value.resetFields()
  // 重置权限 通过keys设置目前勾选的节点，使用此方法设置node-key属性
  tree.value.setCheckedKeys([]);
};

// 数形控件
const defaultProps = {
  children: "children",
  label: "title",
};

// 生命周期 挂载完成
onMounted(() => {
  store.dispatch("menu/getMenuActions");
  store.dispatch("role/getActionsRole");
});

// 数据回显
const lookup = async (id: number) => {
  // console.log(e);
  let res = await roleinfo({ id });
  // console.log(res);
  if (res.code == 200) {
    form.value = res.list;
    form.value.id = id;
    tree.value.setCheckedKeys(form.value.menus.split(","));
  }
};

let roleRef = ref<FormInstance>();
let tree = ref<any>(null);

// 确定
const confirm = async (formEl?: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((val) => {
    if (val) {
      form.value.menus = tree.value.getCheckedKeys().join(",");
      // console.log(form.value);
      if (props.isAdd) {
        roleadd(form.value).then((res) => {
          if (res.code == 200) {
            // console.log(res);
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "success",
            });
            cancel();
            store.dispatch("role/getActionsRole");
          }
        });
      } else {
        roleedit(form.value).then((res) => {
          if (res.code == 200) {
            // console.log(res);
            ElMessage({
              showClose: true,
              message: res.msg,
              type: "success",
            });
            cancel();
            store.dispatch("role/getActionsRole");
          }
        });
      }
    }
  });
};

defineExpose({
  lookup,
});
</script>

<style lang="less" scoped></style>
